package com.kulian.Signalling.system.service.impl.socket.handler;

import com.kulian.Signalling.system.mode.socket.SignalingMessage;
import com.kulian.Signalling.system.service.impl.socket.MessageSender;
import com.kulian.Signalling.system.service.impl.socket.RoomManager;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RequiredArgsConstructor
public class RoomMessageHandler {
    private final RoomManager roomManager;
    private final MessageSender messageSender;

    public void handleCreateRoom(String username) {
        if (roomManager.getUserRoom(username) != null) {
            messageSender.sendError(username, "您已经在其他房间中");
            return;
        }

        String roomId = roomManager.createRoom(username);
        log.info("User[{}] created room[{}]", username, roomId);
        sendRoomInfo(username, roomId);
    }

    public void handleJoinRoom(String username, String roomId) {
        if (roomManager.joinRoom(roomId, username)) {
            sendRoomInfo(username, roomId);
            notifyRoomParticipants(roomId, username, SignalingMessage.MessageType.USER_JOINED);
        } else {
            messageSender.sendError(username, "加入房间失败");
        }
    }

    public void handleLeaveRoom(String username) {
        String roomId = roomManager.getUserRoom(username);
        if (roomId != null) {
            roomManager.leaveRoom(username);
            notifyRoomParticipants(roomId, username, SignalingMessage.MessageType.USER_LEFT);
        }
    }

    private void sendRoomInfo(String username, String roomId) {
        var room = roomManager.getRoom(roomId);
        if (room == null) {
            messageSender.sendError(username, "房间不存在");
            return;
        }

        var message = new SignalingMessage();
        message.setType(SignalingMessage.MessageType.ROOM_INFO.name());
        message.setRoomId(roomId);
        message.setData(room.getParticipants());
        message.setTimestamp(System.currentTimeMillis());
        
        messageSender.sendToUser(username, message);
    }

    private void notifyRoomParticipants(String roomId, String username, SignalingMessage.MessageType type) {
        var room = roomManager.getRoom(roomId);
        if (room == null) return;

        var message = new SignalingMessage();
        message.setType(type.name());
        message.setFrom(username);
        message.setRoomId(roomId);
        message.setTimestamp(System.currentTimeMillis());

        room.getParticipants().stream()
            .filter(participant -> !participant.equals(username))
            .forEach(participant -> messageSender.sendToUser(participant, message));
    }
}
